package com.ruoyi.common.utils;

import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.quartz.CronExpression;

/**
 * 时间工具类
 * 
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    
    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     * 
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     * 
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }
    
    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    public static int getWeekOfYearByF(Date date, int firstDay){
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
        int result;
        if(dayOfWeek >= firstDay + 1){
            result = c.get(Calendar.WEEK_OF_YEAR) + 1;
        } else {
            result = c.get(Calendar.WEEK_OF_YEAR);
        }
        if(result == 1){
            if(c.get(Calendar.MONTH) == 11){
                result = 53;
            }
        }
        return result;
    }

    public static String[] getStartAndEndByWeek(int week, int firstDay){
        Calendar c = Calendar.getInstance();
        Calendar now = Calendar.getInstance();
        c.setWeekDate(c.get(Calendar.YEAR), week, firstDay + 1);
        String firstDayOfYear = String.valueOf(now.get(Calendar.YEAR)) + "-01-01";
        Integer i = firstDayOfYear.compareTo(parseDateToStr(YYYY_MM_DD,c.getTime()));
        String[] result = new String[2];
        if(i == 0) { //i == 0的情况是周五正好是1月1日的情况，这样正好就是第一周
            result[0] = parseDateToStr(YYYY_MM_DD, c.getTime());
            c.add(Calendar.DATE, 6);
            result[1] = parseDateToStr(YYYY_MM_DD, c.getTime());
        } else { //周五不是1月1日的情况
            if(c.get(Calendar.YEAR) == now.get(Calendar.YEAR)){ //c的时间跨度还在本年度的情况
                if(c.get(Calendar.MONTH) == 0 && c.get(Calendar.DATE) < 8 ){ //第一周的情况
                    result[0] = firstDayOfYear;
                    c.add(Calendar.DATE, - 1);
                    result[1] = parseDateToStr(YYYY_MM_DD,c.getTime());
                } else {
                    c.add(Calendar.DATE, - 7);
                    result[0] = parseDateToStr(YYYY_MM_DD, c.getTime());
                    c.add(Calendar.DATE, + 6);
                    result[1] = parseDateToStr(YYYY_MM_DD,c.getTime());
                }
            } else { //c的时间超出了本年度，一般是最后一周
                c.add(Calendar.DATE, - 7);
                result[0] = parseDateToStr(YYYY_MM_DD, c.getTime());
                result[1] = String.valueOf(now.get(Calendar.YEAR)) + "-12-31";
            }
        }
        return result;
    }

    public static int getQuarter(Date date){
        int quarter = 0;
        Calendar cal = Calendar.getInstance();
        int m = cal.get(Calendar.MONTH);
        if(m >= 1 && m <= 3){
            quarter = 1;
        }
        if(m >= 4 && m <= 6){
            quarter = 2;
        }
        if(m >= 7 && m <= 9){
            quarter = 3;
        }
        if(m >= 10 && m <= 12){
            quarter = 4;
        }
        return quarter;
    }

    public static List<String> cronParser(String cronExpression) {
        List<String> result = new ArrayList<String>();
        if (cronExpression == null || cronExpression.length() < 1) {
            return result;
        } else {
            CronExpression exp = null;
            Calendar calendar = Calendar.getInstance();
            String cronDate = calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DATE);
            String sStart = cronDate + " 00:00:00";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dStart = null;
            Date dEnd = null;
            try {
                exp = new CronExpression(cronExpression);
                dStart = sdf.parse(sStart);
                calendar.setTime(dStart);
                calendar.add(Calendar.DATE, 1);
                dEnd = calendar.getTime();
            } catch (ParseException e) {
                e.printStackTrace();
                return result;
            }
            Date dd = new Date();
            dd = exp.getNextValidTimeAfter(dd);
            dd = exp.getNextInvalidTimeAfter(dd);
            while (dd.getTime() < dEnd.getTime()) {
                result.add(sdf.format(dd));
                dd = exp.getNextValidTimeAfter(dd);
            }
            exp = null;
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(DateUtils.getWeekOfYearByF(DateUtils.parseDate("2020-12-24"), 5));
//
    }

}
